package com.zja.www.service.impl;

import com.zja.www.dao.MedicalRecordDao;
import com.zja.www.entity.MedicalRecord;
import com.zja.www.service.MedicalRecordService;


import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

public class MedicalRecordServiceImpl implements MedicalRecordService {
    private final MedicalRecordDao recordDao;

    public MedicalRecordServiceImpl(MedicalRecordDao recordDao) {
        this.recordDao = recordDao;
    }


    @Override
    public boolean createRecord(MedicalRecord record) {

        if (record.getUserId() <= 0 || record.getDoctorId() <= 0 ||
                record.getRecordTime() == null || record.getType() == null) {
            return false;
        }


        if (record.getStatus() == null) {
            record.setStatus(MedicalRecord.STATUS_PENDING);
        }


        if (checkTimeConflict(record.getDoctorId(), record.getRecordTime())) {
            return false;
        }

        return recordDao.insert(record);
    }

    @Override
    public MedicalRecord getRecordById(int id) {
        return recordDao.selectById(id);
    }

    @Override
    public List<MedicalRecord> getRecordsByDoctorAndDate(int doctorId, Timestamp date) {
        return recordDao.selectByDoctorAndTime(doctorId, date);
    }

    @Override
    public boolean updateRecordStatus(int recordId, String newStatus) {

        if (!isValidStatus(newStatus)) {
            return false;
        }
        return recordDao.updateStatus(recordId, newStatus);
    }

    @Override
    public List<MedicalRecord> getRecordsByUser(int userId) {
        return recordDao.selectByUserId(userId);
    }

    @Override
    public boolean cancelRecord(int recordId) {
        return recordDao.updateStatus(recordId, MedicalRecord.STATUS_CANCELLED);
    }

    @Override
    public boolean checkTimeConflict(int doctorId, Timestamp time) {
        // 查询医生该时间段是否有已确认的预约
        List<MedicalRecord> records = recordDao.selectByDoctorAndTime(doctorId, time);
        return records.stream().anyMatch(r ->
                !r.getStatus().equals(MedicalRecord.STATUS_CANCELLED) &&
                        Math.abs(r.getRecordTime().getTime() - time.getTime()) < 30 * 60 * 1000 // 30分钟间隔
        );
    }


    private boolean isValidStatus(String status) {
        return status.equals(MedicalRecord.STATUS_PENDING) ||
                status.equals(MedicalRecord.STATUS_CONFIRMED) ||
                status.equals(MedicalRecord.STATUS_CANCELLED) ||
                status.equals(MedicalRecord.STATUS_COMPLETED);
    }



}

